<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 课程
// +----------------------------------------------------------------------

namespace app\course\controller;

use app\BaseController;
use app\course\model\Course;
use app\course\model\CourseCategory;
use think\facade\View;

class AdminCourseController extends BaseController
{
    /**
     * @OA\Get(path="/course",tags={"课程"},summary="列表",
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="limit", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Response(response="200", description="The User")
     * )
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['id'])) {
                $where[] = ['id', '=', $param['id']];
            }
            if (!empty($param['title'])) {
                $where[] = ['title', 'like', '%' . $param['title'] . '%'];
            }
            if (!empty($param['category_id'])) {
                $where[] = ['category_id', '=', $param['category_id']];
            }
            $list = Course::with(['category' => function ($query) {
                $query->field('id,name');
            }])->where($where)->order('id desc')->paginate(10);
            $data = [
                'code'    => 0,
                'message' => '正在请求中...',
                'count'   => $list->total(),
                'data'    => $list->items()
            ];
            return json($data);
        }
        return View::fetch('admin/app/course/list');
    }

    public function create()
    {
        View::assign([
            'categories' => CourseCategory::field('id,name')->select(),
            'course'    => null
        ]);
        return View::fetch('admin/app/course/listform');
    }

    /**
     * @OA\Post(path="/course",tags={"课程"},summary="新增",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="content-type/json",
     *         @OA\Schema(
     *           @OA\Property(description="文章名称", property="title", type="string"),
     *           @OA\Property(description="文章内容", property="content", type="string"),
     *           required={"title", "content"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function save()
    {
        $param = $this->request->param(['category_id', 'title', 'content', 'stock', 'thumb', 'price', 'sort' ,'status']);
        $param['user_id'] = $this->user_id;
        $param['status']  = isset($param['status']);

        $this->validate($param, 'app\course\validate\Course');
        Course::create($param);
        return $this->success('操作成功');
    }

    /**
     * @OA\Get(path="/course/{id}",tags={"课程"},summary="详情",
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\Response(response="200", description="The User")
     * )
     */
    public function read($id)
    {
        $data = Course::with(['user' => function ($query) {
            $query->field('id,nickname');
        }])->find($id);
        $this->success('获取成功', $data);
    }

    public function edit($id)
    {
        View::assign([
            'categories' => CourseCategory::categories(),
            'course'     => Course::find($id)
        ]);
        return View::fetch('admin/app/course/listform');
    }

    /**
     * @OA\Put(path="/course/{id}",tags={"课程"},summary="编辑",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="content-type/json",
     *         @OA\Schema(
     *           @OA\Property(description="文章名称", property="title", type="string"),
     *           @OA\Property(description="文章内容", property="content", type="string"),
     *           required={"title", "content"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function update($id)
    {
        $param = $this->request->param(['category_id', 'title', 'content', 'stock', 'thumb', 'price', 'sort' ,'status']);
        $param['user_id'] = $this->user_id;
        $param['status']  = isset($param['status']);

        $this->validate($param, 'app\course\validate\Course');

        $course = Course::find($id);
        $course = $course->save($param);
        if (!$course) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * @OA\Delete(path="/course/{id}",tags={"课程"},summary="删除",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function delete($id)
    {
        $res = Course::destroy($id);
        if (!$res) {
            $this->error("删除失败");
        }
        $this->success('删除成功');
    }

    public function destroy()
    {
        $ids = $this->request->param('ids');
        $this->success(json_encode($ids));
    }

    /**
     * @OA\Get(path="/course/top",tags={"课程"},summary="首页推荐",
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\Response(response="200", description="The User")
     * )
     */
    public function top()
    {
        $where[] = ['status', '=', 1];
        $list = Course::with(['category' => function ($query) {
            $query->field('id,name');
        }])->where($where)->order('id', 'desc')->limit(5)->select();
        $this->success('Success', $list);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function list()
    {
        $param = $this->request->param();
        $where = [];
        if (!empty($param['keywords'])) {
            $where[] = ['title', 'like', '%' . $param['keywords'] . '%'];
        }
        if (!empty($param['category_id'])) {
            $where[] = ['category_id', '=', $param['category_id']];
        }
        $list = Course::with(['category' => function ($query) {
            $query->field('id,name');
        }])->where($where)->order('id desc')->paginate(10);
        $data = [
            'code' => 0,
            'message' => '正在请求中...',
            'count' => $list->total(),
            'data' => $list->items()
        ];
        return json($data);
    }

    /**
     * 收藏
     */
    public function collection()
    {
        
    }
}